/**
 * 管理后台 - 首页 - layout
 * Author: Zeon
 * Date: 2017/8/1
 * Created by Panxsoft.
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
@copy-right-height: 48px;
// 整体布局
.layout {
	// background: #f5f7f9;
	position: relative; // overflow: hidden;
	.ivu-row-flex {
		flex-wrap: nowrap;
	}
}

// 左侧导航栏
.layout-side-menu {
	background: #464c5b;
}

// 右侧操作区
.layout-operate-side {
	position: relative;
	padding-bottom: @copy-right-height;
	min-width: 1400px;
	overflow-y: hidden;
}

// 主内容外层
.main-content {
	position: absolute;
	top: 100px;
	bottom: 48px;
	width: 100%;
}

.main-content > div {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	width: 100%;
}

// 版权文字区
.copy-right {
	text-align: center;
	padding: 10px 0 20px;
	color: #9ea7b4;
	position: absolute;
	width: 100%;
	bottom: 0;
	background-color: #f0f0f0;
}

// 侧边栏 + 内容区 伸缩同时过渡
.ivu-col {
	transition: width 0.2s linear;
}


/*tag标签栏样式*/

.tag-line {
	position: relative;
	width: 100%;
	height: 40px;
	box-sizing: border-box;
	background-color: #f0f0f0;
	// box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
	// box-shadow: inset 0 0 3px 2px rgba(99,99,99,.1);
	overflow: hidden;
	.tag-box {
		position: absolute;
		top: 50%;
		white-space: nowrap;
		overflow: visible;
		transform: translateY(-50%);
		transition: left .3s ease;
	}
}


/*tag标签栏样式 END*/

/*导航菜单栏最小宽度限制 START*/

.shrink-menu-width {
    min-width: 60px;
}

.menu-width {
    min-width: 300px;
}

.global-loader{
	z-index: 1500;
	background-color: rgba(255, 255, 255, 0.6);
}

/*导航菜单栏最小宽度限制 END*/
</style>
<template>
	<div class="v-index layout">
		<Row type="flex">
			<i-col
				ref="side_menu"
				:span="span_left"
				:class="{'shrink-menu-width':shrink ,'menu-width':!shrink}"
				class="layout-side-menu">
				<side-menu
					v-if="!shrink"
					:span-left="span_left"

					@change="changeMenuWidth"/>
				<side-shrink-menu
					v-else
					:span-left="span_left"

					@change="changeMenuWidth"/>
			</i-col>

			<!-- 右侧主操作区 BEGIN -->
			<i-col
				ref="operate_wrapper"
				:span="span_right"
				class="layout-operate-side operate-main-wrapper">

				<!-- 顶部导航栏 -->
				<nav-header
					:shrink="shrink"
					@edit-user-info="handleEditUserInfo"
					@toggle-side-bar="toggleClick"/>
				<div
					v-if="getCachepage &&
					getCachepage.length > 0"
					class="tag-line">
					<div
						:style="{left:tag_left + 'px'}"
						class="tag-box"
						@DOMMouseScroll="handlescroll"
						@mousewheel="handlescroll">


						<Tag
							v-for="( page , index ) in getCachepage"
							:key="index"
							:name="index"
							:closable="index !== 0"
							:color="page.name === getSelectedMenu ? 'blue' : ''"
							class="tag-item"
							type="dot"
							checkable
							@click.native="routerTo(page.name)"
							@on-close="closeTag"

						>{{ page.title }}</Tag>
					</div>
				</div>

				<!-- 管理内容区子路由视图 -->
				<div class="main-content">
					<router-view/>
				</div>

				<div class="copy-right">
					<p>2018-{{ year_now }} <em>{{ version }}</em> &copy; Powered by PanxSoft；客服热线：020-82520103；QQ：3239966704</p>
				</div>

				<Spin
					v-show="getSpin"
					fix
					class="global-loader">
					<Icon
						type="load-c"
						size="18"
						class="demo-spin-icon-load"/>
					<div>{{ getSpinText }}</div>
				</Spin>

			</i-col>
		<!-- 右侧主操作区 END -->

		</Row>

		<!-- BEGIN: 编辑用户信息 -->
		<Modal
			v-model="is_visible_user_info"
			:title="$t('template.update_user_info')">
			<div slot="footer"/>
			<Form
				:model="user_info_form"
				:label-width="80">
				<user-edit
					:user-roles="getUserRoles"
					:role-index="getStaffRoleIndex"
					:user-info="getUserInfo"
					@update="handleUpdateUserInfo"/>
			</Form>
		</Modal>
		<!-- END: 编辑用户信息 -->

	</div>
</template>
<script>
import API_LIST from 'src/API_LIST';
import {
	mapGetters,
	mapMutations,
	mapActions,
} from 'vuex';
/* eslint-disable import/no-unresolved */
import { setMinHeightToInnerHeight } from 'src/utils/dom-helper';
import { delay } from 'src/utils/helper';
import sideMenu from './side-menu';
import navHeader from './nav-header';
import sideShrinkMenu from './side-shrink-menu';
import UserEdit from './user-edit';
/* eslint-enable import/no-unresolved */

export default {
	components: {
		'side-menu': sideMenu,
		'nav-header': navHeader,
		sideShrinkMenu,
		'user-edit': UserEdit,
	},

	data() {
		return {
			tag_left: 5,		// position的left值
			span_left: 4,
			menu_width: 0,		// 菜单的宽度
			span_right: 20,
			loading_info: '',
			year_now: new Date().getFullYear(),
			shrink: false,
			is_visible_user_info: false,
			user_info_form: {
				name: null,
				account: null,
				password: null,
				phone: null,
				sex: null,
				born_at: null,
				role_name: null,
			},
			version: API_LIST.VERSION,
		};
	},
	computed: {
		...mapGetters('spinShow', ['getSpin', 'getSpinText']),
		...mapGetters('menu', ['getCachepage', 'getSelectedMenu', 'getUserType']),
		...mapGetters('staff', ['getStaffRoleIndex']),
		...mapGetters('userToken', ['getUserInfo', 'getUserRoles']),

		operateWrapperElem() {
			return this.$refs.operate_wrapper.$el;
		},
	},
	watch: {
		// 监听选中的菜单，自动滑动聚焦到当前的tag
		getSelectedMenu: {
			handler() {
				const cachepages = this.getCachepage;

				const selected_menu = this.getSelectedMenu;

				let selected_index = 0;

				if (cachepages.length === 0) return;

				for (let i = 0; i < cachepages.length; i += 1) {
					const page = cachepages[i];
					if (page.name === selected_menu) {
						selected_index = i;
						break;
					}
				}

				this.$nextTick(() => {
					this.autoFocusTag(selected_index);
				});
			},
		},
	},
	mounted() {
		this.setInnerMinHeight();
		this.fetchInitailStaffDataAction();
		this.resolveMenusAction();

		const menu = document.querySelector('.layout-side-menu');

		this.menu_width = menu.offsetWidth;

		menu.addEventListener('transitionend', this.changeMenuWidth);

		const tage_left = sessionStorage.getItem('tag_left');

		if (tage_left) {
			this.tag_left = Number(tage_left);
		}
	},
	methods: {
		...mapActions('menu', ['resolveMenusAction']),
		...mapMutations('menu', ['deleteCachepage']),
		...mapActions('staff', ['fetchInitailStaffDataAction', 'updateStaffAction']),
		...mapMutations('report', ['clearUserInfos']),

		/**
		 * 限制中间内容区域的高度
		 * @return {undefined}
		 */
		limitMainContentHeight() {
			const main_content = document.querySelector('.main-content');		// 主内容区域
			const nav_header = document.querySelector('.layout-header');		// nav_header
			const tag_area = document.querySelector('.tag-line');				// 标签栏区域
			const copy_right = document.querySelector('.copy-right');			// 底部信息

			const header_height = nav_header ? nav_header.offsetHeight : 0;
			const tag_height = tag_area ? tag_area.offsetHeight : 0;
			const copy_height = copy_right ? copy_right.offsetHeight : 0;

			const pane_height = window.innerHeight - header_height - tag_height - copy_height;	// 88是指tab标签栏头部以及距离tabpane的距离之和

			main_content.style.height = `${pane_height}px`;
		},

		/**
		 * 菜单宽度改变后适应改变滑动
		 * @param {Object} e {事件对象e}
		 * @return {undefined}
		 */
		changeMenuWidth(e) {
			if (e.propertyName !== 'width') return;

			this.handleSelectedMenuChange();
		},

		/**
		 * 处理鼠标滚动的事件
		 * @param  {Object} e {事件对象e}
		 * @return {undefined}
		 */
		handlescroll(e) {
			const tag_box = document.querySelector('.tag-box');
			const tag_line = document.querySelector('.tag-line');

			if ((tag_box.offsetWidth + 5) < tag_line.offsetWidth) return;

			const event_type = e.type;
			let delta = 0;
			if (event_type === 'DOMMouseScroll' || event_type === 'mousewheel') {
				delta = e.wheelDelta ? e.wheelDelta : -(e.detail || 0) * 40;
			}
			let left = 0;
			if (delta > 0) {
				left = Math.min(5, this.tag_left + delta);
			} else if (tag_line.offsetWidth < tag_box.offsetWidth) {
				if (this.tag_left < -((tag_box.offsetWidth - tag_line.offsetWidth))) {
					left = this.tag_left;
				} else {
					left = Math.max(this.tag_left + delta, tag_line.offsetWidth - tag_box.offsetWidth - 5);
				}
			} else {
				this.tag_left = 0;
			}

			this.tag_left = left;
		},

		/**
		 * 选中菜单改变时触发的事件
		 * @return {undefined}
		 */
		handleSelectedMenuChange() {
			const cachepages = this.getCachepage;

			const selected_menu = this.getSelectedMenu;

			let selected_index = 0;

			for (let i = 0; i < cachepages.length; i += 1) {
				const page = cachepages[i];
				if (page.name === selected_menu) {
					selected_index = i;
					break;
				}
			}

			this.autoFocusTag(selected_index);
		},

		/**
		 * 自动滑动到对应的tag
		 * @param  {Number} selected_index {需要滑到的tag的index}
		 * @return {undefined}
		 */
		autoFocusTag(selected_index) {
			const current_tag = document.querySelectorAll('.tag-item')[selected_index];

			const current_left_distance = current_tag.offsetLeft;
			const current_width = current_tag.offsetWidth;

			const tag_line = document.querySelector('.tag-line');

			const tag_line_width = tag_line.offsetWidth;

			if ((current_left_distance + current_width) > tag_line_width) {
				this.tag_left = -((current_left_distance - tag_line_width) + current_width + 5);
			} else if (current_left_distance < Math.abs(this.tag_left)) {
				this.tag_left = -(current_left_distance - 5);
			}

			sessionStorage.setItem('tag_left', this.tag_left);
		},

		/**
		 * 返回首页
		 * @return {undefined}
		 */
		// toHome() {
		// let home_route = '';
		// switch (this.getUserType) {
		// case 'panx':
		// 	home_route = '/admin/';

		// 	break;
		// case 'customer':
		// 	home_route = '/customer/';

		// 	break;
		// default:
		// 	home_route = '/store/';

		// 	break;
		// }
		// this.$router.push({
		// 	path: '/admin/',
		// });
		// },

		/**
		 * 路由跳转
		 * @param  {string} path {路径}
		 * @return {undefined}
		 */
		routerTo(path) {
			this.$router.push({
				path,
			});
		},

		/**
		 * 关闭tag标签
		 * @param  {Object} e    {事件event对象}
		 * @param  {string} name {tag的name属性}
		 * @return {undefined}
		 */
		closeTag(e, name) {
			if (this.getCachepage[name].name === '/customer/skin-test-detail') {
				this.clearUserInfos();
			}
			this.deleteCachepage(name);
		},

		/**
		 * 隐藏侧边导航栏
		 * @param  {Bool} is_bar_open {布尔值}
		 * @return {undefined}
		 */
		toggleClick(is_bar_open) {
			if (!is_bar_open) {
				this.span_left = 1;
				this.span_right = 23;
			} else {
				this.span_left = 4;
				this.span_right = 20;
			}
			this.shrink = !this.shrink;
		},

		setInnerMinHeight() {
			this.listenResizeSetInnerHeight();
			// this.limitMainContentHeight();
			setMinHeightToInnerHeight(this.operateWrapperElem);
		},

		listenResizeSetInnerHeight() {
			const delaySetInnerHeight = delay(this.setInnerMinHeight.bind(this), 500); // 包装成延时函数
			window.addEventListener('resize', () => delaySetInnerHeight());
		},

		/**
		 *  处理编辑用户信息事件
		 *  @return {undefined}
		 */
		handleEditUserInfo() {
			this.showUserInfoEditor();
		},

		/**
		 *  显示用户信息编辑框
		 *  @return {undefined}
		 */
		showUserInfoEditor() {
			this.is_visible_user_info = true;
		},

		/**
		 *  隐藏用户信息编辑框
		 *  @return {undefined}
		 */
		hideUserInfoEditor() {
			this.is_visible_user_info = false;
		},

		/**
		 *  更新用户信息
		 *  @param {Object} form {更新表单参数}
		 *  @return {undefined}
		 */
		handleUpdateUserInfo(form) {
			this.updateStaffAction(form)
				.then((data) => {
					if (data) {
						this.$Message.success(this.$t('common.operate_success'));
						this.hideUserInfoEditor();
					}
				});
		},
	},
};
</script>
